const network = require("../utils/network");
const util = require("../utils/util");
module.exports = Behavior({
    behaviors: [],
    properties: {
        requestUrl: {
            type: String
        },
        requestData: {
            type: Object
        },
    },
    data: {
        listParams: {
            page: 1,
            page_size: 20,
            total: 0,
            pages: 0
        },
        list: [],
    },
    methods: {
        getList(isAdd = false) {
            const _this = this
            return new Promise((resolve, reject) => {
                util.showLoading('加载中')
                network.GET({
                    uri: _this.properties.requestUrl,
                    params: Object.assign({}, _this.data.listParams, _this.properties.requestData),
                    success(res) {
                        _this.setData({
                            'listParams.page': res.data.current,
                            'listParams.total': res.data.total,
                            'listParams.pages': res.data.pages || 1,
                            list: isAdd ? ([].concat(_this.data.list, res.data.records || [])) : (res.data.records || [])
                        })
                        if (!isAdd) wx.stopPullDownRefresh()
                        util.hideLoading()
                        resolve(res)
                    },
                    fail() {
                        if (!isAdd) wx.stopPullDownRefresh()
                        util.hideLoading()
                        reject()
                    }
                })
            })
        },
        handlePullDownRefresh() {
            const _this = this
            _this.setData({
                'listParams.page': 1
            }, function () {
                _this.getList()
            })
        },
        handleReachBottom() {
            const _this = this
            if(_this.data.listParams.pages > _this.data.listParams.page){
              _this.setData({
                'listParams.page': _this.data.listParams.page + 1
              }, function () {
                _this.getList(true).catch(() => {
                    _this.setData({
                        'listParams.page': _this.data.listParams.page - 1
                    })
                })
              })
            }
        }
    },
    pageLifetimes: {
        // 组件所在页面的生命周期函数
        show() {
            if (this.data.disableShow) {
                return
            }
            this.getList()
        },
    },
})